package pipeline

import (
	"blockchain/public/entity"
	"blockchain/public/function"
	"encoding/json"
	"time"
)

type requestMessage struct {
	tradeSet [TradeSize] entity.Trade //对应requestSet
	sign string
	clientSeq int
}

func genTrades(){//生成TradeSize笔交易
	time1 :=time.Now()
	for i:=currentTradeSeq;i<currentTradeSeq+TradeSize;i++{
		trades[i].Sender=string(rune(i%26+65))//+fmt.Sprint(i%50)
		trades[i].Receiver=string(rune(i%26+97))//+fmt.Sprint(i%50)
		trades[i].Timestamp=time1
		trades[i].Remainder=5//余额
		trades[i].Send=2
		time1=time1.Add(1*time.Microsecond)
	}
	currentTradeSeq=currentTradeSeq+TradeSize
}

func request(round int){
	updatePrimarys()
	genTrades()
	var request requestMessage
	for i:=0;i<TradeSize;i++{
		request.tradeSet[i]=trades[round*TradeSize+i]
	}
	data,_:=json.Marshal(&request.tradeSet)
	request.sign=function.Sign(data,clientSeq)
	request.clientSeq=clientSeq
	var flagRequested=make([]chan bool,N)
	for i:=range primarysSeq{
		flagRequested[primarysSeq[i]]=make(chan bool,1)
		chanPriRecRequest[primarysSeq[i]]=make(chan requestMessage,1)
		go sendRequestToPriNode(flagRequested[i],primarysSeq[i],request)
	}
	for i:=range primarysSeq{
		<-flagRequested[primarysSeq[i]]
	}
}

func sendRequestToPriNode(flagRequested chan bool,priSeq int,request requestMessage){
	//chanPriRecRequest[priSeq]<-request
	select {
		case chanPriRecRequest[priSeq]<-request:
			close(chanPriRecRequest[priSeq])
		default:println("request写入通道错误")
	}
	flagRequested<-true
	close(flagRequested)
}

func request1(round int){
	updatePrimarys()
	genTrades()
	var request requestMessage
	for i:=0;i<TradeSize;i++{
		request.tradeSet[i]=trades[round*TradeSize+i]
	}
	data,_:=json.Marshal(&request.tradeSet)
	request.sign=function.Sign(data,clientSeq)
	request.clientSeq=clientSeq
	var flagRequested=make([]chan bool,N)
	for i:=range primarysSeq{
		flagRequested[primarysSeq[i]]=make(chan bool,1)
		chanPriRecRequest2[primarysSeq[i]]=make(chan requestMessage,1)
		go sendRequestToPriNode1(flagRequested[i],primarysSeq[i],request)
	}
	for i:=range primarysSeq{
		<-flagRequested[primarysSeq[i]]
	}
}

func sendRequestToPriNode1(flagRequested chan bool,priSeq int,request requestMessage){
	//chanPriRecRequest[priSeq]<-request
	select {
	case chanPriRecRequest2[priSeq]<-request:
		close(chanPriRecRequest2[priSeq])
	default:println("request写入通道错误")
	}
	flagRequested<-true
	close(flagRequested)
}



